﻿using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Http.Controllers;
using XieCan.AspMVC.JWTAuth;

namespace XieCan.AspMVC.WebApi
{
#pragma warning disable CS1591 // 缺少对公共可见类型或成员“ApiAuthorizeAttribute”的 XML 注释
    public class ApiAuthorizeAttribute : AuthorizeAttribute
#pragma warning restore CS1591 // 缺少对公共可见类型或成员“ApiAuthorizeAttribute”的 XML 注释
    {
        /// <summary>
        /// 指示指定的控件是否已获得授权
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            //前端请求api时会将token存放在名为"auth"的请求头中
            var authHeader = from t in actionContext.Request.Headers where t.Key == "Authorization" select t.Value.FirstOrDefault();
            if (authHeader != null)
            {
                string token = authHeader.FirstOrDefault();//获取token
                if (!string.IsNullOrWhiteSpace(token))
                {
                    try
                    {
                        //解密
                        var result = JWTHelper.Decoder(token);
                        if (result.Success)
                        {
                            var tokens = result.Data;
                            var role = tokens["Role"]?.ToString();
                            if (string.IsNullOrWhiteSpace(Roles) || Roles.Contains(role))
                            {
                                actionContext.RequestContext.RouteData.Values.Add("Authorization", result.Data);
                                return true;
                            }
                            return false;
                        }
                        return false;
                    }
                    catch (Exception)
                    {
                        return false;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 处理授权失败的请求
        /// </summary>
        /// <param name="actionContext"></param>
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            base.HandleUnauthorizedRequest(actionContext);
            using (HttpResponseMessage response = actionContext.Response ?? new HttpResponseMessage())
            {
                response.StatusCode = HttpStatusCode.Forbidden;
                var content = new
                {
                    stausCode = "403",
                    success = false,
                    errs = new[] { "服务端拒绝访问：你没有权限，或者掉线了" }
                };
                response.Content = new StringContent(Json.Encode(content), Encoding.UTF8, "application/json");
            }

        }
    }
}